package com.sakura.mybatis.version3.doctor.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.sakura.mybatis.version3.doctor.vo.PersonalInfoVO;
import com.sakura.mybatis.version3.doctor.vo.ProjectVO;
import com.sakura.mybatis.version3.mapper.DataMapper;
import com.sakura.mybatis.version3.utils.SqlSessionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;

import java.util.List;
import java.util.Map;

/**
 * @Author Sakura
 * @Date 2023/6/12 14:33
 * @Version 1.0
 */
@Slf4j
public class PersonalInfoVOListener extends AnalysisEventListener<PersonalInfoVO> {
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 1000;

    private static int count = 0;

    /**
     * 缓存的数据
     */
    private List<PersonalInfoVO> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);


    @Override
    public void invoke(PersonalInfoVO projectVO, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(projectVO));
        cachedDataList.add(projectVO);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    //读取表头内容
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        System.out.println("表头信息:" + JSON.toJSONString(headMap));

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！共{}条数据", count);
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());

        SqlSession sqlSession = null;
        try {
            String pathName = "config/mybatis/version3/mybatis-config.xml";
            sqlSession = SqlSessionUtils.getSqlSession(pathName, false);
            DataMapper mapper = sqlSession.getMapper(DataMapper.class);
            for (PersonalInfoVO patientVO : cachedDataList) {
                mapper.batchInsertPersonal(patientVO);
            }
            sqlSession.commit();
            sqlSession.clearCache();
            count += cachedDataList.size();
            log.info("存储数据库成功！");
        } catch (Exception e) {
            count -= cachedDataList.size();
            sqlSession.rollback();
            log.error("插入异常!异常消息：{}", e);
        } finally {
            if (null != sqlSession) {
                sqlSession.close();
            }
        }
    }
}
